// pages/demo-omi-page/index.js
import router from "@src/router";
const QR = require('./weapp-qrcode') //引入weapp-qrcode
let extConfig = wx.getExtConfigSync ? wx.getExtConfigSync() : {};
import { orderDetail, getInfo, cancelOrderFunc, confirmReceiptFunc, deleteOrder, createOrder,pollOrder,checkProtectTime } from "../../api/order"
import {getGoodsAndShopJoinPayChannels} from "@src/api/mall/store";
import $math from '@src/common/math'
import base from "@src/store/base";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import { getDistance } from "@src/common/utils";
import mall from "@src/store/mall";
import mallPayBehavior from "@mall/pages/submit-order/mallPayBehavior";
import {fanyCountdown} from "../../utils/util"
import dayjs from "dayjs";
Component({
  behaviors: [storeBindingsBehavior, mallPayBehavior],
  storeBindings: [{
    store: base,
    fields: ['isiPhoneX', 'themeColor', 'themeTitleColor']
  }, {
    store: mall,
    actions: ['initLocation','goodsAndShopJoinPay']
  }],
  data: {
    pollTimer:'',
    isPoll:false,
    bookingStatus:null,
    //商品类型 VIRTUAL: 虚拟商品, EXPRESS:快递, LOCAL:同城(自提)
    type: null,
    //店铺信息
    storeInfo: null,
    //订单状态 WAITING: 待支付, PAYED: 已支付(待发货/待提货), UNDERWAY: 服务中, FINISH: 已完成, CANCEL: 已取消
    status: null,
    subStatus: null,
    //商品数组
    items: null,
    //虚拟商品数组包含的券
    ticketList: [],
    //配送信息
    delivery: null,
    //支付信息
    payInfo: null,
    //下单信息
    orderInfo: null,
    //最好支付时间
    payDeadline: null,
    //剩余支付时间
    remaiPayTime: null,
    //应付金额
    tradeFee: null,
    //订单更新时间
    updateTime: null,
    //隐藏支付控件
    hiddenPay: true,
    //支付方式
    payType: null,
    supportBALANCE: false,
    supportWX: false,
    //订单记录
    statusRecords: null,
    //余额
    personBalance: null,
    newtimer: null,
    isVirtual: false,
    //支付时间
    storeDistance: 0,
    toStoreTime: "",
    hiddenSelfCode: true,
    // businessId: null,
    businessId: extConfig.businessId,
    userName: "",
    nickName: "",
    //传给子组件的支付金额
    payMoney: 0,
    //商家备注
    remark: "",
    //订单备注
    orderRemark: "",
    //子订单类型, DEFAULT: 普通订单, FULL_PRESELL:全额预售, DEPOSIT_PRESELL:定金预售
    subType: null,
    orderPresell: null,
    orderObj: null,
    isCanPayRemaining: false,
    qrcodeURL:"",//提取码二维码
    activityGroup:null,//拼团活动相关信息
    shutDownTime:null,//拼团活动关闭时间
    timeInterval:null,
    shareGroupImg:null,
    whiteTiemEnd:false,
  },
  observers: {
    'orderObj': function (orderObj) {
      if (orderObj) {
        //定金支付
        if (this.data.subType === 'DEPOSIT_PRESELL' && orderObj.orderPresell.depositStatus === 0) {
          this.setData({
            tradeFee: $math.div(orderObj.orderPresell.depositFee, 100)
          })
        }
        //尾款支付
        else if (this.data.subType === 'DEPOSIT_PRESELL' && orderObj.orderPresell.depositStatus === 1) {
          this.setData({
            tradeFee: $math.div(orderObj.orderPresell.remainingFee, 100)
          })
        } else {
          this.setData({
            tradeFee: $math.div(orderObj.tradeFee, 100)
          })
        }
      }
    },
    'hiddenSelfCode':function(value){
      if(this.data.isPoll){
        console.log(this.data.isPoll,value,'555555556565656656')
        return
      }
      value?this.startAndClearPoll(1):this.startAndClearPoll()
    }
  },

  options: {
    addGlobalClass: true,
  },
  pageLifetimes:{

  },
  methods: {
    onShow(){
      // if(this.data.activityGroup){
      //     clearInterval(this.data.timeInterval)
      //     const wxObj=this;
      //     fanyCountdown(this.data.activityGroup.expireTime,wxObj)
      // }
      if(this.data.orderInfo&&this.data.orderInfo.orderNo){
        this.getOrderDetailFunc(this.data.orderInfo.orderNo);
      }
    },
    onHide(){
      clearInterval(this.data.timeInterval)
    },
    groupInviteFriends(){

    },
    onShareAppMessage: function (res) {
      if (res.from === 'button') {
        // 来自页面内转发按钮
        console.log(res.target)
      }
      return {
        title: this.data.items[0].title,
        path: `sp-mall/pages/join-group/index?groupNo=${this.data.activityGroup.groupNo}`,
        imageUrl: this.data.shareGroupImg||getApp().toFullUrl(this.data.items[0].coverImg),
      }
    },
    // 获取拼团海报
    groupPainter(e){
      console.log('海报',e.detail)
      // this.data.shareGroupImg=e.detail;
      this.setData({shareGroupImg:e.detail})
    },
    toSpellGroupPer:function (){
      //leaderCollect: 是否代收字段
      router.push({name:"mall/spellGroupPer",params:{orderNo:this.data.orderInfo.orderNo,status:this.data.status}})

    },
    //提取码二维码
    drawImgFn: function (takeNo){
      const params = takeNo;  // 二维码参数
      var imgData = QR.drawImg(params, {
        typeNumber: 4,          // 密度
        errorCorrectLevel: 'L', // 纠错等级
        size: 800,              // 白色边框
      })

      this.setData({
        qrcodeURL: imgData
      })
    },
    //获取订单详情
    async getOrderDetailFunc(orderNo) {
      clearInterval(this.data.newtimer)
      clearInterval(this.data.timeInterval)
      const self = this;
      await orderDetail(orderNo).then(res => {
        if (res.code == 0) {
          let orderInfo = {
            orderNo: res.data.orderNo,
            createTime: res.data.createTime
          }
          if( res.data.statusRecords[0].remark){
            self.setData({statusRecords : res.data.statusRecords[0].remark})
          }
          if(res.data.remark){
            self.setData({remark: res.data.remark})
          }
          //处理拼团中图像地址
          if(res.data.activityGroup){
            let fileBaseUrl = getApp().globalData.extConfig.fileBaseUrl;
            res.data.activityGroup.userList.forEach((v,i)=>{
             if(!v.headImg.includes('http')) v.headImg=fileBaseUrl+'/'+v.headImg
            })
          }

          if(res.data.activityGroup&&!res.data.activityGroup.isCreator&&res.data.activityGroup.leaderCollect){
            const reg = /^(\d{3})\d{4}(\d{4})$/;
            res.data.delivery.phone = res.data.delivery.phone.replace(reg, "$1****$2");
          }
          if(res.data.delivery&&res.data.delivery.leaderCollect&&res.data.activityGroup){
             for(let i in res.data.activityGroup.leaderDelivery){
               res.data.delivery[i]=res.data.activityGroup.leaderDelivery[i]
             }
          }
          self.setData({
            type: res.data.type,
            storeInfo: res.data.store,
            status: res.data.status,
            subStatus: res.data.subStatus,
            items: res.data.items,
            delivery: res.data.delivery,
            payInfo: res.data.payInfo,
            orderInfo: orderInfo,
            //payDeadline: "2020-07-15 20:09:00",
            tradeFee: res.data.tradeFee,
            allDiscountFee: res.data.allDiscountFee,
            payDeadline: res.data.payDeadline,
            updateTime: res.data.updateTime,
            orderAmounts: res.data.orderAmounts,
            activityGroup:res.data.activityGroup?res.data.activityGroup:null,//拼团相关数据
            subType: res.data.subType,
            orderObj: res.data
          });
          self.resetData(res.data,res);
          console.log("type", this.data.type);
          console.log("orderObj", this.data.orderObj)
          //获取提取码二维码链接
          if(res.data.delivery&&res.data.delivery.takeNo) self.drawImgFn(res.data.delivery.takeNo)
          self.getDistanceByStore();
          //获取倒计时
          if(res.data.activityGroup) {
              const wxObj=this;
              fanyCountdown(res.data.activityGroup.expireTime,wxObj)
          }

        } else {
          showToast({
            title: 'res.msg',
            icon: 'none'
          })
        }
        console.log(res)
      })
    },
    resetData(data,res) {
      if (data.bizData) {
        let orderRemark = JSON.parse(data.bizData);
        let remark = orderRemark.remark ? orderRemark.remark : '';
        this.setData({ orderRemark: remark })
      }
      //判断是否时虚拟商品,虚拟商品的券包
      if (this.data.type === 'VIRTUAL') {
        this.setData({ isVirtual: true })
        this.data.items[0].items.forEach(item => { item.tickethidden = true })
        this.setData({ ticketList: this.data.items[0].items })
      }
      /**
       * 判断是否需要倒计时:
       *  1.普通订单未支付的状态都需要倒计时
       *  2.预售订单
       *      2-1：未支付定金需要倒计时
       *      2-2：全款预售，未付款需要倒计时
       */
      const self = this;
      if (this.data.status == 'WAITING') {
        if (data.subType === 'DEFAULT' ||
          data.subType === 'FULL_PRESELL' ||
          (data.subType === 'DEPOSIT_PRESELL' && data.orderPresell.depositStatus == 0) ||
            data.subType === 'SEC_KILL'
        ) {
          self.setData({
            newtimer: setInterval(function () {
              self.usetime(res)
            }, 1000)
          })
        }
      }
      if (data.orderPresell) { this.setData({ orderPresell: data.orderPresell }) };
      //判断下现在是否能支付尾款
      let startTime = new Date().getTime() || '';
      if(data.goodsPresellVo){
        let remainingBeginTime = new Date(data.goodsPresellVo.remainingBeginTime.replace(/\-/g, '/')).getTime() || '';
        let dis = startTime - remainingBeginTime; // 相差的毫秒数;
        console.log('dis', dis)
        //可以支付尾款
        if (dis > 0) {
          this.setData({ isCanPayRemaining: true })
        } else {
          this.setData({ isCanPayRemaining: false })
        }
        this.setData({bookingStatus : true})
      }
      this.setData({goodsPresellVo:data.goodsPresellVo})

    },
    cancelPreSellOrder() {

    },
    //获取店铺距离我的距离
    getDistanceByStore() {
      const self = this;
      let storeInfo = this.data.storeInfo;
      if (!storeInfo) {
        return;
      }
      this.initLocation().then(res => {
        let distance = getDistance(res.latitude, res.longitude, storeInfo.latitude, storeInfo.longitude)
        if (distance < 1000) {
          self.setData({
            storeDistance: distance + "米"
          })
        } else {
          distance = (Math.round(distance / 100) / 10).toFixed(1) + "km"
          self.setData({
            storeDistance: distance
          })
        }
      })
    },
    openMap() {
      wx.openLocation({//​使用微信内置地图查看位置。
        latitude: this.data.storeInfo.latitude,//要去的纬度-地址
        longitude: this.data.storeInfo.longitude,//要去的经度-地址
      })
    },
    //获取自提时间  没用了现在
    getSelfTimeFunc() {
      console.log("获取自提时间")
      let delivery = this.data.delivery;
      if (delivery.arrivalTime) {
        let date = new Date(delivery.arrivalTime);
        console.log('date', date)
        let flag = date.getMonth() + 1 + "月" + date.getDate() + "日"

        if ((date.getHours() + "").length < 2) {
          flag = flag + "0" + "" + (date.getHours() + "") + ":00";
        }
        this.setData({
          toStoreTime: flag
        })
        console.log("toStoreTime", this.data.toStoreTime)
      }

    },
    //设置倒计时
    usetime(res) {
      const self = this;
      let startTime =dayjs(new Date()).valueOf() || '';
      let endTime = new Date(this.data.payDeadline.replace(/\-/g, '/')).getTime() || '';
      let dis = endTime - startTime; // 相差的毫秒数;
      //如果倒计时小于0，设置状态为过期
      if (dis < 0) {
        this.setData({whiteTiemEnd:true});
        this.fetchData()


        let orderNo = this.data.orderInfo.orderNo
        // self.data.newtimer ? clearInterval(self.data.newtimer) : ""
        // this.setData({
        //   status: 'CANCEL'
        // })
        // setTimeout(()=>{
        //   self.getOrderDetailFunc(orderNo)
        // },1000)
      }
      if (self.data.status == 'CANCEL') {
        self.data.newtimer ? clearInterval(self.data.newtimer) : ""
      }
      let s = 0; // 秒
      let m = 0; // 分钟
      let h = 0; // 小时
      let d = 0; // 天
      if (dis > 0) {
        dis = Math.floor(dis / 1000);
      }
      if (dis > 0) {
        s = dis % 60;
        dis = Math.floor(dis / 60);
      }
      if (dis > 0) {
        m = dis % 60;
        dis = Math.floor(dis / 60);
      }
      if (dis > 0) {
        h = dis % 60;
        dis = Math.floor(dis / 60);
      }
      if (dis > 0) {
        d = dis % 24;
      }
      this.setData({
        remaiPayTime: h > 0 ? h + '小时' + m + '分钟' + s + '秒' : m + '分钟' + s + '秒'
      })
    },
    //再次购买
    buyAgainFunc() {
      let goodsSerial = this.data.items[0].goodsSerial;
      let storeId = this.data.storeId
      let data = {
        goodsSerial: this.data.items[0].goodsSerial,
        storeId: this.data.items[0].storeId
      }
      router.push({ name: "mall/goods-detail", params: data })
    },
    //取消订单
    cancelFunc() {
      let {orderInfo:{orderNo},tradeFee} = this.data
      checkProtectTime({orderNo}).then(res=>{
        if(res.code == 0){
          if(this.data.status == 'WAITING' || (this.data.subType==='DEPOSIT_PRESELL' && this.data.orderPresell.depositStatus===1)){
            res.data.refundOperateType = 4
          }
          let {refundOperateAmt,refundOperateRatio:cancelChargeRatio,refundOperateType:orderType,resultMsg} = res.data
          let cancelPrice = refundOperateAmt / 100
          let content = 
          orderType == 1?'此订单不支持取消':
          orderType == 4?'是否确定取消订单？':
          orderType == 3?'此订单超出售后时效，请联系商家处理':
          orderType == 2?`取消订单需扣除实付金额的${cancelChargeRatio}% （${cancelPrice < 0.01?'0.00':cancelPrice}元），预计退回${cancelPrice < 0.01?tradeFee:(tradeFee - cancelPrice).toFixed(2)}元，是否确定取消订单`:
          '取消订单后实付金额将原路返回，确认要取消订单吗？' 
          let showCancel = orderType == 3 || orderType == 1?false:true
          let confirmText = orderType == 3 || orderType == 1?'我知道了':'确定'
          const self = this;
          if (this.data.businessId == '33') {
            wx.showToast({
              title: '取消订单请联系商户',
              icon: 'none'
            })
            return;
          }
          if (this.data.subType != 'DEFAULT') {
            let orderPresell = this.data.orderObj.orderPresell;
            if (this.data.subType === 'DEPOSIT_PRESELL' && orderPresell.depositStatus === 1) {
              this.selectComponent("#goodSaleCancelDialog").open();
              return;
            }
            if ((this.data.subType === 'FULL_PRESELL' && orderPresell.remainingStatus === 1)) {
              this.selectComponent("#goodSaleCancelDialog").open();
              return;
            }
          }
          wx.showModal({
            title: '提示',
            content,
            showCancel,
            confirmText,
            success(res) {
              if (res.confirm) {
                if(orderType == 3 || orderType == 1) return
                let orderCancelForm = {
                  orderNo: self.data.orderInfo.orderNo
                }
                cancelOrderFunc(orderCancelForm).then(res => {
                  if (res.code == 0) {
                    wx.showToast({
                      title: '取消成功',
                      icon: 'none'
                    })
                  }
                  else {
                    wx.showToast({
                      title: res.msg,
                      icon: 'none'
                    })
                  }
                  self.getOrderDetailFunc(self.data.orderInfo.orderNo)
                })
              }
            }
          })
        }
        })
    },
    //预售取消订单
    cancelPreSellFunc() {
      let orderCancelForm = {
        orderNo: this.data.orderInfo.orderNo
      }
      cancelOrderFunc(orderCancelForm).then(res => {
        if (res.code == 0) {
          wx.showToast({
            title: '取消成功',
            icon: 'none'
          })
        }
        else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
        this.getOrderDetailFunc(this.data.orderInfo.orderNo)
      })
    },

    // 获取商品购买的支付方式
    buyChannelsFun(){
      return new Promise(resolve => {
        let buyChannels = ''
        let idArr = []
        let goodsIdList = this.data.items
        goodsIdList.forEach(el => {
          idArr.push(el.goodsId)
        })
        let parmData = {
          goodsIdList:idArr,
          storeId:this.data.storeInfo.storeId,
        }
        getGoodsAndShopJoinPayChannels(parmData).then(res => {
          console.log('getGoodsAndShopJoinPayChannels',res)
          buyChannels = res.data
          resolve(buyChannels)
        })
      })
    },

    //去支付
    async toPay() {
	  const payCross = await this.goodsAndShopJoinPay(this.data.orderObj.totalFee,this.data.orderObj.items,this.data.orderObj.store.storeId)
      if(!payCross){
       return
      }
      // if(!this.data.isPwdInit) {
      //   router.push({ name: "member/resetPassword", params: { type: "init" } })
      //   return
      // }

      const buyChannels = await this.buyChannelsFun()
      
      let orderNo = this.data.orderInfo.orderNo;
      let payChannels = [];
      if (this.data.storeInfo.payChannels.indexOf("WX") !== -1 && buyChannels.supplyWxPay) {
        payChannels.push("wx")
      }
      if (this.data.storeInfo.payChannels.indexOf("BALANCE") !== -1 && buyChannels.supplyBalance) {
        payChannels.push("balance")
      }
      let data = {
        orderNo: orderNo,
        payFee: this.data.tradeFee * 100,
        payChannels: payChannels,
        hasDiscount: this.data.allDiscountFee > 0
      }
      //定金支付
      if (this.data.subType === 'DEPOSIT_PRESELL' && this.data.orderObj.orderPresell.depositStatus === 0) {
        console.log("定金")
        data.orderNo = this.data.orderObj.orderPresell.depositOrderNo;
        // data.payFee = this.data.orderPresell.depositFee;
      }
      //支付尾款
      if (this.data.subType === 'DEPOSIT_PRESELL' && this.data.orderObj.orderPresell.depositStatus === 1 && this.data.orderObj.orderPresell.remainingStatus === 0) {
        if (!this.data.isCanPayRemaining) {
          wx.showToast({
            title: '未到尾款支付时间',
            icon: "none"
          })
          return;
        }
        // data.payFee = this.data.orderPresell.depositFee;
      }
        this.toMallPay(data).then(res => {
        console.info("成功", res)
        this.selectComponent("#toast").show({ icon: "", txt: "支付成功", type: 'info', time: 2000 });
        this.getOrderDetailFunc(orderNo)
      }).catch(res => {
        if (res && res.code === "cancel") {
          return;
        }
        // 支付失败
        this.selectComponent("#toast").show({ icon: "error", txt: res.msg, type: 'info', time: 2000 });
        this.getOrderDetailFunc(orderNo)
      })
    },
    //确认收货
    confirmReceipt() {
      const self = this;
      let orderNo = this.data.orderInfo.orderNo
      console.log('this.data.orderInfo', this.data.orderInfo.orderNo)
      confirmReceiptFunc(orderNo).then(res => {
        if (res.code == 0) {
          wx.showToast({
            title: '确认收货成功'
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
        self.getOrderDetailFunc(orderNo)
      })
    },
    //去个人中心页
    checkAccount() {
      let isShopMall = true
      wx.switchTab({
        url: '/pages/mine/main?isShopMall=' + isShopMall,
      })
    },
    //删除订单
    deleteOrderFunc() {
      const self = this;


      wx.showModal({
        title: "确认删除订单？",
        content: "删除后订单将无法恢复，确认要删除吗？",
        cancelText: "点错了",
        confirmText: "删除",
        confirmColor: "#F56C6C",
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            deleteOrder(self.data.orderInfo.orderNo).then(res => {
              if (res.code == 0) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                setTimeout(() => {
                  wx.navigateBack({})
                  const eventChannel = self.getOpenerEventChannel()
                  eventChannel.emit('acceptDataFromOpenedPage', { data: 'test' });
                  // wx.navigateTo({
                  //   url: '/pages/memberCardModule/pages/myOrderList/main',
                  //   success: function (res) {
                  //     // 通过eventChannel向被打开页面传送数据
                  //     res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
                  //   }

                  // })
                }, 1000)
              }

            }).catch(error => {
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            })
          } else if (res.cancel) {

            console.log('用户点击取消')
          }
        }
      })
    },
    //监听支付框是否隐藏
    setHiddentrueFunc() {
      console.log("刷新页面")
      const self = this;
      self.getOrderDetailFunc(self.data.orderInfo.orderNo)
      // wx.navigateTo({
      //     url: '/pages/shop-mall/order-detail/index?orderNo=' + self.data.orderNo
      //   })
    },

    //显示自提码
    selfCodeShow() {
      this.setData({
        hiddenSelfCode: false
      })
    },
    changeCodeVal(e){
      this.setData({hiddenSelfCode:e.detail.value})
    },
    // 提货码被打开一直轮询页面
    startAndClearPoll(type){
      const _that = this
      if(!type){
        this.data.pollTime = setInterval(() => {
          pollOrder({orderNo:this.data.orderInfo.orderNo}).then(res=>{
            if(res.code == 0){
              if(res.data.success){
                wx.showModal({
                  title: '提示',
                  content: `你的商城到店自提订单${this.data.orderInfo.orderNo}已经在${res.data.shopName}被核销`,
                  showCancel:false,
                  success(res) {
                    if (res.confirm) {
                    }
                  }
                })
                _that.setData({isPoll:true})
                _that.getOrderDetailFunc(_that.data.orderInfo.orderNo);
                _that.setData({hiddenSelfCode: true})
                clearInterval(_that.data.pollTime)
              }
            }
          })
        }, 1000);
      }else{
        console.log(22222222,type)
        clearInterval(this.data.pollTime)
      }
    },
    callLeaterPhone(e){
      const phone = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
        phoneNumber: phone //仅为示例，并非真实的电话号码
      })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.$pay = this.selectComponent("#pay");
      let orderNo = options.orderNo
      this.getOrderDetailFunc(orderNo);
      let stores = wx.getStorageSync('memberInfo');
      console.log('stores', stores)
      this.setData({
        nickName: stores.wechat_nickname
      })
      console.log('nickName', this.data.nickName)
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
      this.data.newtimer ? clearInterval(this.data.newtimer) : ""
      clearInterval(this.data.pollTime)
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
      this.getOrderDetailFunc(this.data.orderInfo.orderNo);
      setTimeout(() => {
        wx.stopPullDownRefresh();
      }, 1000)

    },
  }
})
